"""
技术分析策略模块

基于技术指标实现的交易策略，支持趋势跟踪、均值回归、突破等策略。
"""

from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from enum import Enum
import pandas as pd
try:
    import numpy as np
except ImportError:
    np = None  # type: ignore

# 类型检查时的numpy替代
if np is None:
    class NumpyMock:
        def sqrt(self, x: float) -> float:
            return x ** 0.5
    np = NumpyMock()  # type: ignore

from .base_strategy import (
    BaseStrategy, StrategyConfig, StrategyType, RiskLevel,
    Signal, SignalType, Position, StrategyMetrics
)
from ..analysis.market_analysis import (
    MarketAnalyzer, TrendDirection
)

# 定义技术指标类型枚举
class TechnicalIndicatorType(Enum):
    """技术指标类型"""
    RSI = "rsi"
    MACD = "macd"
    BOLLINGER_BANDS = "bollinger_bands"
    SMA = "sma"
    EMA = "ema"
    STOCHASTIC = "stochastic"
    ATR = "atr"
    CCI = "cci"


class TechnicalStrategyType(Enum):
    """技术策略类型"""
    TREND_FOLLOWING = "trend_following"  # 趋势跟踪
    MEAN_REVERSION = "mean_reversion"  # 均值回归
    MOMENTUM = "momentum"  # 动量策略
    BREAKOUT = "breakout"  # 突破策略
    OSCILLATOR = "oscillator"  # 震荡策略
    MULTI_INDICATOR = "multi_indicator"  # 多指标组合


@dataclass
class IndicatorConfig:
    """技术指标配置"""
    indicator_type: TechnicalIndicatorType
    parameters: Dict[str, Any] = field(default_factory=dict)  # 指标参数
    weight: float = 1.0  # 权重
    enabled: bool = True  # 是否启用
    signal_threshold: Dict[str, float] = field(default_factory=dict)  # 信号阈值


@dataclass
class TechnicalStrategyConfig(StrategyConfig):
    """技术分析策略配置"""
    technical_strategy_type: TechnicalStrategyType = TechnicalStrategyType.TREND_FOLLOWING
    indicators: List[IndicatorConfig] = field(default_factory=list)  # 技术指标配置
    lookback_period: int = 50  # 回看期
    signal_confirmation_period: int = 3  # 信号确认期
    stop_loss_pct: float = 0.05  # 止损百分比
    take_profit_pct: float = 0.10  # 止盈百分比
    trailing_stop_pct: float = 0.03  # 移动止损百分比
    min_signal_strength: float = 0.6  # 最小信号强度
    max_signal_strength: float = 1.0  # 最大信号强度
    signal_decay_factor: float = 0.9  # 信号衰减因子
    volume_confirmation: bool = True  # 是否需要成交量确认
    min_volume_ratio: float = 1.2  # 最小成交量比率
    trend_filter: bool = True  # 是否使用趋势过滤
    volatility_filter: bool = True  # 是否使用波动率过滤
    max_volatility: float = 0.05  # 最大波动率
    
    def __post_init__(self) -> None:
        """初始化后处理"""
        # 移除super().__post_init__()调用，因为StrategyConfig没有这个方法
        self.strategy_type = StrategyType.TECHNICAL
        
        # 如果没有配置指标，使用默认配置
        if not self.indicators:
            self._setup_default_indicators()
    
    def _setup_default_indicators(self) -> None:
        """设置默认指标配置"""
        if self.technical_strategy_type == TechnicalStrategyType.TREND_FOLLOWING:
            self.indicators = [
                IndicatorConfig(
                    indicator_type=TechnicalIndicatorType.SMA,
                    parameters={"period": 20},
                    weight=0.4,
                    signal_threshold={"buy": 1.02, "sell": 0.98}
                ),
                IndicatorConfig(
                    indicator_type=TechnicalIndicatorType.MACD,
                    parameters={"fast": 12, "slow": 26, "signal": 9},
                    weight=0.6,
                    signal_threshold={"buy": 0.0, "sell": 0.0}
                )
            ]
        elif self.technical_strategy_type == TechnicalStrategyType.MEAN_REVERSION:
            self.indicators = [
                IndicatorConfig(
                    indicator_type=TechnicalIndicatorType.RSI,
                    parameters={"period": 14},
                    weight=0.5,
                    signal_threshold={"oversold": 30, "overbought": 70}
                ),
                IndicatorConfig(
                    indicator_type=TechnicalIndicatorType.BOLLINGER_BANDS,
                    parameters={"period": 20, "std_dev": 2},
                    weight=0.5,
                    signal_threshold={"lower": 0.1, "upper": 0.9}
                )
            ]
        else:
            # 默认多指标组合
            self.indicators = [
                IndicatorConfig(
                    indicator_type=TechnicalIndicatorType.RSI,
                    parameters={"period": 14},
                    weight=0.3
                ),
                IndicatorConfig(
                    indicator_type=TechnicalIndicatorType.MACD,
                    parameters={"fast": 12, "slow": 26, "signal": 9},
                    weight=0.4
                ),
                IndicatorConfig(
                    indicator_type=TechnicalIndicatorType.SMA,
                    parameters={"period": 20},
                    weight=0.3
                )
            ]


class TechnicalStrategy(BaseStrategy):
    """技术分析策略类"""
    
    def __init__(self, config: TechnicalStrategyConfig):
        """
        初始化技术分析策略
        
        Args:
            config: 技术分析策略配置
        """
        super().__init__(config)
        self.config: TechnicalStrategyConfig = config
        self.market_analyzer = MarketAnalyzer()
        
        # 技术指标相关状态
        self._indicator_values: Dict[str, Dict[str, Any]] = {}  # 指标值
        self._signal_history: Dict[str, List[Signal]] = {}  # 信号历史
        self._trend_direction: Dict[str, TrendDirection] = {}  # 趋势方向
        self._volatility_levels: Dict[str, float] = {}  # 波动率水平
        self._volume_ratios: Dict[str, float] = {}  # 成交量比率
        
        # 止损止盈相关
        self._stop_loss_levels: Dict[str, float] = {}  # 止损位
        self._take_profit_levels: Dict[str, float] = {}  # 止盈位
        self._trailing_stops: Dict[str, float] = {}  # 移动止损位
    
    async def initialize(self) -> bool:
        """
        初始化策略
        
        Returns:
            bool: 初始化是否成功
        """
        try:
            # 验证指标配置
            if not self.config.indicators:
                self.error_message = "未配置技术指标"
                return False
            
            # 验证权重总和
            total_weight = sum(ind.weight for ind in self.config.indicators if ind.enabled)
            if total_weight <= 0:
                self.error_message = "指标权重总和必须大于0"
                return False
            
            # 初始化技术指标
            for indicator_config in self.config.indicators:
                if indicator_config.enabled:
                    await self._initialize_indicator(indicator_config)
            
            return True
            
        except Exception as e:
            self.error_message = f"策略初始化失败: {str(e)}"
            return False
    
    async def _initialize_indicator(self, indicator_config: IndicatorConfig) -> None:
        """
        初始化技术指标
        
        Args:
            indicator_config: 指标配置
        """
        # 这里可以添加指标初始化逻辑
        # 例如预加载历史数据、设置参数等
        pass
    
    async def generate_signals(self, data: Dict[str, pd.DataFrame]) -> List[Signal]:
        """
        生成交易信号
        
        Args:
            data: 市场数据，key为标的代码，value为价格数据
            
        Returns:
            List[Signal]: 交易信号列表
        """
        try:
            signals = []
            current_time = datetime.now()
            
            for symbol, price_data in data.items():
                if len(price_data) < self.config.lookback_period:
                    continue
                
                # 计算技术指标
                indicator_signals = await self._calculate_indicator_signals(symbol, price_data)
                
                # 应用过滤器
                if not self._apply_filters(symbol, price_data):
                    continue
                
                # 生成综合信号
                composite_signal = self._generate_composite_signal(
                    symbol, indicator_signals, current_time
                )
                
                if composite_signal:
                    signals.append(composite_signal)
                
                # 检查止损止盈信号
                stop_signals = self._check_stop_signals(symbol, price_data, current_time)
                signals.extend(stop_signals)
            
            return signals
            
        except Exception as e:
            self.error_message = f"信号生成失败: {str(e)}"
            return []
    
    async def _calculate_indicator_signals(self, symbol: str, 
                                         data: pd.DataFrame) -> Dict[str, Dict[str, Any]]:
        """
        计算技术指标信号
        
        Args:
            symbol: 标的代码
            data: 价格数据
            
        Returns:
            Dict[str, Dict[str, Any]]: 指标信号
        """
        indicator_signals = {}
        
        try:
            for indicator_config in self.config.indicators:
                if not indicator_config.enabled:
                    continue
                
                indicator_type = indicator_config.indicator_type
                parameters = indicator_config.parameters
                
                # 计算指标值
                indicator_result = None
                signal_info = None
                
                if indicator_type == TechnicalIndicatorType.RSI:
                    from ..analysis.market_analysis import TechnicalIndicator
                    indicator_result = await self.market_analyzer.calculate_technical_indicator(
                        data, TechnicalIndicator.RSI, **parameters
                    )
                    signal_info = self._analyze_rsi_signal(indicator_result, indicator_config)
                    
                elif indicator_type == TechnicalIndicatorType.MACD:
                    from ..analysis.market_analysis import TechnicalIndicator
                    indicator_result = await self.market_analyzer.calculate_technical_indicator(
                        data, TechnicalIndicator.MACD, **parameters
                    )
                    signal_info = self._analyze_macd_signal(indicator_result, indicator_config)
                    
                elif indicator_type == TechnicalIndicatorType.BOLLINGER_BANDS:
                    from ..analysis.market_analysis import TechnicalIndicator
                    indicator_result = await self.market_analyzer.calculate_technical_indicator(
                        data, TechnicalIndicator.BOLLINGER_BANDS, **parameters
                    )
                    signal_info = self._analyze_bollinger_signal(indicator_result, indicator_config)
                    
                elif indicator_type == TechnicalIndicatorType.SMA:
                    sma_value = await self._calculate_sma(data, parameters.get("period", 20))
                    signal_info = self._analyze_sma_signal(data, sma_value, indicator_config)
                    indicator_result = {"value": sma_value}  # 为SMA创建结果对象
                    
                else:
                    continue
                
                if signal_info:
                    indicator_signals[indicator_type.value] = signal_info
                    
                    # 保存指标值
                    if symbol not in self._indicator_values:
                        self._indicator_values[symbol] = {}
                    # 保存指标结果
                    if indicator_result is not None:
                        self._indicator_values[symbol][indicator_type.value] = indicator_result
            
            return indicator_signals
            
        except Exception as e:
            self.error_message = f"指标信号计算失败: {str(e)}"
            return {}
    
    def _analyze_rsi_signal(self, rsi_result: Any, 
                           config: IndicatorConfig) -> Optional[Dict[str, Any]]:
        """
        分析RSI信号
        
        Args:
            rsi_result: RSI计算结果
            config: 指标配置
            
        Returns:
            Optional[Dict[str, Any]]: 信号信息
        """
        try:
            if not hasattr(rsi_result, 'value') or rsi_result.value is None:
                return None
            
            current_rsi = float(rsi_result.value)
            thresholds = config.signal_threshold
            
            oversold = thresholds.get("oversold", 30)
            overbought = thresholds.get("overbought", 70)
            
            if current_rsi <= oversold:
                return {
                    "signal_type": SignalType.BUY,
                    "strength": min((oversold - current_rsi) / oversold, 1.0),
                    "confidence": 0.8,
                    "reason": f"RSI超卖: {current_rsi:.2f}"
                }
            elif current_rsi >= overbought:
                return {
                    "signal_type": SignalType.SELL,
                    "strength": min((current_rsi - overbought) / (100 - overbought), 1.0),
                    "confidence": 0.8,
                    "reason": f"RSI超买: {current_rsi:.2f}"
                }
            
            return None
            
        except Exception:
            return None
    
    def _analyze_macd_signal(self, macd_result: Any, 
                            config: IndicatorConfig) -> Optional[Dict[str, Any]]:
        """
        分析MACD信号
        
        Args:
            macd_result: MACD计算结果
            config: 指标配置
            
        Returns:
            Optional[Dict[str, Any]]: 信号信息
        """
        try:
            if not hasattr(macd_result, 'value') or not isinstance(macd_result.value, dict):
                return None
            
            macd_values = macd_result.value
            if 'macd' not in macd_values or 'signal' not in macd_values:
                return None
            
            macd_line = float(macd_values['macd'])
            signal_line = float(macd_values['signal'])
            histogram = macd_line - signal_line
            
            # MACD金叉死叉信号
            if histogram > 0 and macd_line > signal_line:
                return {
                    "signal_type": SignalType.BUY,
                    "strength": min(abs(histogram) / abs(macd_line) if macd_line != 0 else 0, 1.0),
                    "confidence": 0.7,
                    "reason": f"MACD金叉: {macd_line:.4f} > {signal_line:.4f}"
                }
            elif histogram < 0 and macd_line < signal_line:
                return {
                    "signal_type": SignalType.SELL,
                    "strength": min(abs(histogram) / abs(macd_line) if macd_line != 0 else 0, 1.0),
                    "confidence": 0.7,
                    "reason": f"MACD死叉: {macd_line:.4f} < {signal_line:.4f}"
                }
            
            return None
            
        except Exception:
            return None
    
    def _analyze_bollinger_signal(self, bb_result: Any, 
                                 config: IndicatorConfig) -> Optional[Dict[str, Any]]:
        """
        分析布林带信号
        
        Args:
            bb_result: 布林带计算结果
            config: 指标配置
            
        Returns:
            Optional[Dict[str, Any]]: 信号信息
        """
        try:
            if not hasattr(bb_result, 'value') or not isinstance(bb_result.value, dict):
                return None
            
            bb_values = bb_result.value
            if not all(key in bb_values for key in ['upper', 'lower', 'middle']):
                return None
            
            upper_band = float(bb_values['upper'])
            lower_band = float(bb_values['lower'])
            middle_band = float(bb_values['middle'])
            
            # 假设当前价格是middle_band（简化处理）
            current_price = middle_band
            
            # 计算价格在布林带中的位置
            band_width = upper_band - lower_band
            if band_width <= 0:
                return None
            
            position = (current_price - lower_band) / band_width
            
            thresholds = config.signal_threshold
            lower_threshold = thresholds.get("lower", 0.1)
            upper_threshold = thresholds.get("upper", 0.9)
            
            if position <= lower_threshold:
                return {
                    "signal_type": SignalType.BUY,
                    "strength": min((lower_threshold - position) / lower_threshold, 1.0),
                    "confidence": 0.6,
                    "reason": f"价格接近布林带下轨: {position:.2f}"
                }
            elif position >= upper_threshold:
                return {
                    "signal_type": SignalType.SELL,
                    "strength": min((position - upper_threshold) / (1 - upper_threshold), 1.0),
                    "confidence": 0.6,
                    "reason": f"价格接近布林带上轨: {position:.2f}"
                }
            
            return None
            
        except Exception:
            return None
    
    async def _calculate_sma(self, data: pd.DataFrame, period: int) -> float:
        """
        计算简单移动平均线
        
        Args:
            data: 价格数据
            period: 周期
            
        Returns:
            float: SMA值
        """
        try:
            if len(data) < period:
                return 0.0
            
            close_prices = data['close'].tail(period)
            return float(close_prices.mean())
            
        except Exception:
            return 0.0
    
    def _analyze_sma_signal(self, data: pd.DataFrame, sma_value: float, 
                           config: IndicatorConfig) -> Optional[Dict[str, Any]]:
        """
        分析SMA信号
        
        Args:
            data: 价格数据
            sma_value: SMA值
            config: 指标配置
            
        Returns:
            Optional[Dict[str, Any]]: 信号信息
        """
        try:
            if sma_value <= 0 or len(data) == 0:
                return None
            
            current_price = float(data['close'].iloc[-1])
            price_ratio = current_price / sma_value
            
            thresholds = config.signal_threshold
            buy_threshold = thresholds.get("buy", 1.02)
            sell_threshold = thresholds.get("sell", 0.98)
            
            if price_ratio >= buy_threshold:
                return {
                    "signal_type": SignalType.BUY,
                    "strength": min((price_ratio - 1.0) * 10, 1.0),
                    "confidence": 0.6,
                    "reason": f"价格突破SMA: {current_price:.2f} > {sma_value:.2f}"
                }
            elif price_ratio <= sell_threshold:
                return {
                    "signal_type": SignalType.SELL,
                    "strength": min((1.0 - price_ratio) * 10, 1.0),
                    "confidence": 0.6,
                    "reason": f"价格跌破SMA: {current_price:.2f} < {sma_value:.2f}"
                }
            
            return None
            
        except Exception:
            return None
    
    def _apply_filters(self, symbol: str, data: pd.DataFrame) -> bool:
        """
        应用过滤器
        
        Args:
            symbol: 标的代码
            data: 价格数据
            
        Returns:
            bool: 是否通过过滤器
        """
        try:
            # 趋势过滤器
            if self.config.trend_filter:
                if not self._check_trend_filter(symbol, data):
                    return False
            
            # 波动率过滤器
            if self.config.volatility_filter:
                if not self._check_volatility_filter(symbol, data):
                    return False
            
            # 成交量过滤器
            if self.config.volume_confirmation:
                if not self._check_volume_filter(symbol, data):
                    return False
            
            return True
            
        except Exception:
            return False
    
    def _check_trend_filter(self, symbol: str, data: pd.DataFrame) -> bool:
        """
        检查趋势过滤器
        
        Args:
            symbol: 标的代码
            data: 价格数据
            
        Returns:
            bool: 是否通过趋势过滤器
        """
        try:
            # 简化的趋势判断：比较短期和长期均线
            if len(data) < 50:
                return True
            
            short_ma = data['close'].tail(10).mean()
            long_ma = data['close'].tail(50).mean()
            
            # 保存趋势方向
            if short_ma > long_ma:
                self._trend_direction[symbol] = TrendDirection.UPTREND
            elif short_ma < long_ma:
                self._trend_direction[symbol] = TrendDirection.DOWNTREND
            else:
                self._trend_direction[symbol] = TrendDirection.SIDEWAYS
            
            return True
            
        except Exception:
            return True
    
    def _check_volatility_filter(self, symbol: str, data: pd.DataFrame) -> bool:
        """
        检查波动率过滤器
        
        Args:
            symbol: 标的代码
            data: 价格数据
            
        Returns:
            bool: 是否通过波动率过滤器
        """
        try:
            if len(data) < 20:
                return True
            
            # 计算20日波动率
            returns = data['close'].pct_change().tail(20)
            if np is not None:
                volatility = returns.std() * np.sqrt(252)  # 年化波动率
            else:
                volatility = returns.std() * (252 ** 0.5)  # 年化波动率
            
            self._volatility_levels[symbol] = volatility
            
            return volatility <= self.config.max_volatility
            
        except Exception:
            return True
    
    def _check_volume_filter(self, symbol: str, data: pd.DataFrame) -> bool:
        """
        检查成交量过滤器
        
        Args:
            symbol: 标的代码
            data: 价格数据
            
        Returns:
            bool: 是否通过成交量过滤器
        """
        try:
            if 'volume' not in data.columns or len(data) < 20:
                return True
            
            # 计算成交量比率
            current_volume = data['volume'].iloc[-1]
            avg_volume = data['volume'].tail(20).mean()
            
            if avg_volume <= 0:
                return True
            
            volume_ratio = current_volume / avg_volume
            self._volume_ratios[symbol] = volume_ratio
            
            return volume_ratio >= self.config.min_volume_ratio
            
        except Exception:
            return True
    
    def _generate_composite_signal(self, symbol: str, indicator_signals: Dict[str, Dict[str, Any]], 
                                 timestamp: datetime) -> Optional[Signal]:
        """
        生成综合信号
        
        Args:
            symbol: 标的代码
            indicator_signals: 指标信号
            timestamp: 信号时间
            
        Returns:
            Optional[Signal]: 综合信号
        """
        try:
            if not indicator_signals:
                return None
            
            # 计算加权信号
            buy_score = 0.0
            sell_score = 0.0
            total_weight = 0.0
            signal_reasons = []
            
            for indicator_config in self.config.indicators:
                if not indicator_config.enabled:
                    continue
                
                indicator_name = indicator_config.indicator_type.value
                if indicator_name not in indicator_signals:
                    continue
                
                signal_info = indicator_signals[indicator_name]
                weight = indicator_config.weight
                strength = signal_info.get("strength", 0.0)
                signal_type = signal_info.get("signal_type")
                reason = signal_info.get("reason", "")
                
                if signal_type == SignalType.BUY:
                    buy_score += strength * weight
                    signal_reasons.append(f"买入-{reason}")
                elif signal_type == SignalType.SELL:
                    sell_score += strength * weight
                    signal_reasons.append(f"卖出-{reason}")
                
                total_weight += weight
            
            if total_weight <= 0:
                return None
            
            # 标准化得分
            buy_score /= total_weight
            sell_score /= total_weight
            
            # 确定最终信号
            if buy_score > sell_score and buy_score >= self.config.min_signal_strength:
                signal_type = SignalType.BUY
                strength = min(buy_score, self.config.max_signal_strength)
                confidence = min(buy_score * 0.8, 0.9)
            elif sell_score > buy_score and sell_score >= self.config.min_signal_strength:
                signal_type = SignalType.SELL
                strength = min(sell_score, self.config.max_signal_strength)
                confidence = min(sell_score * 0.8, 0.9)
            else:
                return None
            
            # 创建信号
            signal = Signal(
                symbol=symbol,
                signal_type=signal_type,
                strength=strength,
                confidence=confidence,
                timestamp=timestamp,
                metadata={
                    "strategy_type": "technical_analysis",
                    "technical_strategy_type": self.config.technical_strategy_type.value,
                    "buy_score": buy_score,
                    "sell_score": sell_score,
                    "reasons": signal_reasons,
                    "trend_direction": self._trend_direction.get(symbol, TrendDirection.SIDEWAYS).value,
                    "volatility": self._volatility_levels.get(symbol, 0.0),
                    "volume_ratio": self._volume_ratios.get(symbol, 1.0)
                }
            )
            
            # 保存信号历史
            if symbol not in self._signal_history:
                self._signal_history[symbol] = []
            self._signal_history[symbol].append(signal)
            
            # 限制历史长度
            if len(self._signal_history[symbol]) > 100:
                self._signal_history[symbol] = self._signal_history[symbol][-100:]
            
            return signal
            
        except Exception as e:
            self.error_message = f"综合信号生成失败: {str(e)}"
            return None
    
    def _check_stop_signals(self, symbol: str, data: pd.DataFrame, 
                           timestamp: datetime) -> List[Signal]:
        """
        检查止损止盈信号
        
        Args:
            symbol: 标的代码
            data: 价格数据
            timestamp: 信号时间
            
        Returns:
            List[Signal]: 止损止盈信号列表
        """
        signals: List[Signal] = []
        
        try:
            if symbol not in self.positions or len(data) == 0:
                return signals
            
            position = self.positions[symbol]
            current_price = float(data['close'].iloc[-1])
            
            # 检查止损
            if symbol in self._stop_loss_levels:
                stop_loss = self._stop_loss_levels[symbol]
                if ((position.quantity > 0 and current_price <= stop_loss) or
                    (position.quantity < 0 and current_price >= stop_loss)):
                    
                    signal = Signal(
                        symbol=symbol,
                        signal_type=SignalType.SELL if position.quantity > 0 else SignalType.BUY,
                        strength=1.0,
                        confidence=0.95,
                        timestamp=timestamp,
                        metadata={
                            "signal_reason": "stop_loss",
                            "stop_price": stop_loss,
                            "current_price": current_price
                        }
                    )
                    signals.append(signal)
            
            # 检查止盈
            if symbol in self._take_profit_levels:
                take_profit = self._take_profit_levels[symbol]
                if ((position.quantity > 0 and current_price >= take_profit) or
                    (position.quantity < 0 and current_price <= take_profit)):
                    
                    signal = Signal(
                        symbol=symbol,
                        signal_type=SignalType.SELL if position.quantity > 0 else SignalType.BUY,
                        strength=0.8,
                        confidence=0.9,
                        timestamp=timestamp,
                        metadata={
                            "signal_reason": "take_profit",
                            "target_price": take_profit,
                            "current_price": current_price
                        }
                    )
                    signals.append(signal)
            
            # 更新移动止损
            self._update_trailing_stop(symbol, current_price, position)
            
            return signals
            
        except Exception as e:
            self.error_message = f"止损止盈检查失败: {str(e)}"
            return []
    
    def _update_trailing_stop(self, symbol: str, current_price: float, position: Position) -> None:
        """
        更新移动止损
        
        Args:
            symbol: 标的代码
            current_price: 当前价格
            position: 持仓信息
        """
        try:
            if position.quantity == 0:
                return
            
            trailing_pct = self.config.trailing_stop_pct
            
            if position.quantity > 0:  # 多头持仓
                new_stop = current_price * (1 - trailing_pct)
                if symbol not in self._trailing_stops or new_stop > self._trailing_stops[symbol]:
                    self._trailing_stops[symbol] = new_stop
                    self._stop_loss_levels[symbol] = new_stop
            else:  # 空头持仓
                new_stop = current_price * (1 + trailing_pct)
                if symbol not in self._trailing_stops or new_stop < self._trailing_stops[symbol]:
                    self._trailing_stops[symbol] = new_stop
                    self._stop_loss_levels[symbol] = new_stop
                    
        except Exception:
            pass